package com.hanggold.captcha.core;

import com.hanggold.captcha.Captcha;
import com.hanggold.captcha.execption.CaptchaException;
import com.hanggold.captcha.pojo.CaptchaEntity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * 抽象公共实现.
 *
 * @author <a href="mailto:free@hanggold.com">free</a>
 * @date 2021-09-29 22:15
 * @since 1.0.0
 **/
@Slf4j
public abstract class CaptchaAbstract implements Captcha {
    
    @Override
    public final CaptchaEntity base64() {
        return doBase64();
    }
    
    private CaptchaEntity doBase64() {
        try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) {
            String value = write(byteOutputStream);
            String base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(byteOutputStream.toByteArray());
            return new CaptchaEntity(value, base64);
        } catch (IOException e) {
            log.error("生成base64为图片验证码失败", e);
        }
        throw new CaptchaException("create captcha base64 error");
    }
    
    /**
     * 写入验证码.
     *
     * @param outputStream outputStream
     * @return string
     */
    @SneakyThrows
    @Override
    public String write(final OutputStream outputStream) {
        char[] targetCaptcha = alphas();
        final String standardWeightChar = standardWeightChar();
        buildImage(outputStream, standardWeightChar, weight(), height(), imageType(), targetCaptcha);
        return String.valueOf(targetCaptcha);
    }
    
}
